<template>
  <div>
    <el-dialog
      v-model="dialogVisible"
      append-to-body
      clas="t-dialog"
      :title="title"
      @close="handleClose"
    >
      <el-select
        size="default"
        v-model="configForm.templateId"
        class="w60 select-width"
        @change="handleMsgContent"
      >
        <el-option
          v-for="item in msgTemplateList"
          :key="item.id"
          :label="item.templateName"
          :value="item.id"
        >
          <span class="float-left">
            {{ item.templateName }}
          </span>
          <span class="float-right ml10">
            <el-tag
              type="success"
              size="default"
            >
              {{ item.templateTypeDesc }}
            </el-tag>
          </span>
        </el-option>
      </el-select>

      <div class="desc-text">
        {{ $t("form.configParams.selectFormFieldComponents") }}
        <el-link
          href="/msg/template"
          type="primary"
          :underline="false"
          target="_blank"
        >
          {{ $t("form.configParams.configureMessageTemplate") }}
        </el-link>
      </div>
      <div class="content-wrap">
        <div class="left-wrap">
          <div
            v-if="!loading"
            class="mt10"
          >
            <div v-if="dynamicFields.length == 0">
              <el-empty :description="$t('form.configParams.templateNotConfigured')" />
            </div>

            <div
              v-for="field in dynamicFields"
              :key="field"
              class="mt10"
            >
              {{ $t("form.configParams.templateVariables") }}
              <el-tag type="info">
                {{ field }}
              </el-tag>
              {{ $t("form.configParams.formComponents") }}
              <el-select
                v-model="templateParamMapping[field]"
                class="select-width"
                size="default"
              >
                <el-option
                  v-for="item in fields"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </div>
          </div>
        </div>
        <div class="right-wrap">
          <div
            class="template-content"
            v-html="formatTemplateContent"
          ></div>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button
            size="default"
            @click="dialogVisible = false"
          >
            {{ $t("formI18n.all.cancel") }}
          </el-button>
          <el-button
            size="default"
            type="primary"
            @click="handleSubmit"
          >
            {{ $t("formI18n.all.confirm") }}
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="ConfigTemplate">
import { computed, onMounted, ref } from "vue";
import { listMsgTemplate, MsgTemplate } from "@/api/system/msgtemplate";
import { FieldItem } from "@/api/project/form";
import { i18n } from "@/i18n";

const msgTemplateList = ref<MsgTemplate[]>([]);

const props = defineProps({
  fields: {
    type: Array as () => FieldItem[],
    required: true
  },
  title: {
    type: String,
    required: true,
    default: i18n.global.t("form.configParams.configTemplateVariables")
  }
});

const templateParamMapping = ref<{ [key: string]: any }>({});
const dialogVisible = ref(false);
const dynamicFields = ref<string[]>([]);
const loading = ref(true);
const templateContent = ref("");

const show = (settings: any) => {
  dialogVisible.value = true;
  configForm.value = settings;
  handleMsgContent();
};

const handleMsgContent = () => {
  loading.value = true;
  const item = msgTemplateList.value.find(item => item.id === configForm.value.templateId);
  if (item) {
    dynamicFields.value = [];
    const regex = /\${([^}]+)}/g;
    const matches = item.templateContent.matchAll(regex);
    for (const match of matches) {
      const extractedString = match[1];
      dynamicFields.value.push(extractedString);
    }
  }
  let initVal = configForm.value.templateParamMapping || {};
  dynamicFields.value.forEach(field => {
    templateParamMapping.value[field] = initVal[field];
  });
  templateContent.value = item?.templateContent || "";
  loading.value = false;
};

const formatTemplateContent = computed(() => {
  let formatContent = templateContent.value;
  Object.keys(templateParamMapping).forEach((key: string) => {
    if (templateParamMapping.value[key]) {
      const item = props.fields.find(item => item.value === templateParamMapping.value[key]);
      formatContent = formatContent.replace("${" + key + "}", item?.label || "");
    }
  });
  return formatContent;
});

defineExpose({
  show
});

const emit = defineEmits(["submit", "close"]);

const handleSubmit = async () => {
  dialogVisible.value = false;
  const val = {
    ...configForm.value,
    templateType: msgTemplateList.value.find(item => item.id === configForm.value.templateId)?.templateType,
    templateParamMapping: templateParamMapping.value
  };
  emit("submit", val);
};

onMounted(() => {
  listMsgTemplate({}).then(res => {
    msgTemplateList.value = res.data;
  });
});

const handleClose = () => {
  emit("close");
};

const configForm = ref<any>({
  templateId: null
});
</script>
<style lang="scss" scoped>
.content-wrap {
  display: flex;
}
.left-wrap {
  width: 50%;
}
.right-wrap {
  width: 50%;
  margin-top: 20px;
  background: #f5f7fa;
  border-radius: 10px;
}
.template-content {
  padding: 20px;
}
.select-width {
  width: 40% !important;
}

.desc-text {
  display: flex;
  gap: 10px;
}
</style>
